package com.StarStudio.Controller;

import com.StarStudio.Service.OrderService;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.Entity.*;
import com.ruoyi.common.core.utils.QueryPageUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;


@RestController
//@RequestMapping("/orders")
public class OrderController {

    @Autowired
    OrderService orderService;

    /**
     * 条件查询 订单分页接口
     * @param orders 订单对象
     * @return 分页结果对象 PageResult
     */
    @GetMapping("/page/{flag}")
    public PageResult page(Orders orders, @PathVariable int flag){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<Orders> ordersList;
        long allRecordNumber;
        if (flag == 0){ //查询全部记录
            try {
                ordersList = orderService.findOrdersList(orders);
                allRecordNumber = orderService.findAllRecordNumber();
                pageInfo = new PageInfo<>(ordersList);
            } catch (Exception e) {
                e.printStackTrace();
                return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
            }
        } else if (flag == 1) { //查询商品订单记录
            try {
                ordersList = orderService.findGoodsOrdersList(orders);
                allRecordNumber = orderService.findAllGoodsRecordNumber();
                pageInfo = new PageInfo<>(ordersList);
            } catch (Exception e) {
                e.printStackTrace();
                return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
            }
        }else { //查询优惠券订单记录
            try {
                SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
                if (!sysUser.isAdmin()){
                    return new PageResult(HttpStatusCode.ERROR,MessageConstant.NORMAL_STORE_CAN_NOT_GET_COUPONS_ORDERS);
                }
                ordersList = orderService.findCouponsOrdersList(orders);
                allRecordNumber = orderService.findAllCouponsRecordNumber();
                pageInfo = new PageInfo<>(ordersList);
            } catch (Exception e) {
                e.printStackTrace();
                return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
            }
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PAGE_SUCCESS, pageInfo.getTotal(), ordersList, allRecordNumber);
    }

    /**
     * 新增订单
     * @param orders 订单对象
     * @return 结果对象 Result
     */
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping("/post")
    public Result NewOrder(@RequestBody Orders orders){
        try {
            orderService.NewOrder(orders);
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("商品库存不足！")){
                return new Result(HttpStatusCode.WARNING,MessageConstant.OUT_OF_GOODS_STOCK);
            } else if (e.getMessage().equals("优惠券库存不足！")) {
                return new Result(HttpStatusCode.WARNING,MessageConstant.OUT_OF_COUPONS_STOCK);
            } else if (e.getMessage().equals("该订单已不可取消！")) {
                return new Result(HttpStatusCode.WARNING,MessageConstant.CAN_NOT_CANCEL_ORDER);
            }else {
                return new Result(HttpStatusCode.ERROR,MessageConstant.SERVER_ERROR);
            }
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.ADD_ORDER_SUCCESS);
    }

    /**
     * 修改订单
     * @param orders 订单对象
     * @return 结果对象 Result
     */
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping("/put")
    public Result UpdateOrder(@RequestBody Orders orders){
        try {
            orderService.UpdateOrder(orders);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_ORDER_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_ORDER_SUCCESS);
    }

    /**
     * 根据订单ID取消订单
     * @param order_id 订单ID
     * @return 结果对象 Result
     */
    @Log(title = "订单管理", businessType = BusinessType.CANCEL)
    @DeleteMapping("/{order_id}")
    public Result CancelOrder(@PathVariable long order_id){
        try {
            orderService.CancelOrder(order_id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.CANCEL_ORDER_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.CANCEL_ORDER_SUCCESS);
    }

    /**
     * 导出订单信息到 Excel表格
     * @param response http响应
     * @param orders 订单对象
     */
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Orders orders) {
        List<Orders> list = orderService.findOrdersList(orders);
        ExcelUtil<Orders> util = new ExcelUtil<>(Orders.class);
        util.exportExcel(response, list, "订单数据");
    }

    /*
     * 远程调用接口
     */
    @PostMapping("/orderInsert")
    void OrderInsert(@RequestBody Orders orders){
        orderService.OrderInsert(orders);
    }

    /*
     * 远程调用接口
     */
    @RequestMapping("/NewOrderNumberToday")
    int New_order_number_today(@RequestParam(value = "today") String today){
        return orderService.New_order_number_today(today);
    }

    /*
     * 远程调用接口
     */
    @RequestMapping("/AllRecordForAdmin")
    long findAllRecordForAdmin(){
        return orderService.findAllRecordForAdmin();
    }

    @RequestMapping("/ByStoreIdAndTime/{store_id}")
    List<Orders> findOrdersByStoreIdAndTime(@PathVariable(value = "store_id") Long store_id, @RequestParam(value = "today") String today){
        List<Orders> ordersByStoreIdAndTime = orderService.findOrdersByStoreIdAndTime(store_id, today);
        if (CollectionUtils.isEmpty(ordersByStoreIdAndTime)){
            return null;
        }
        return ordersByStoreIdAndTime;
    }

    @RequestMapping("/OrdersByStoreId/{store_id}")
    List<Orders> findOrdersByStoreId(@PathVariable(value = "store_id") Long store_id){
        List<Orders> ordersByStoreId = orderService.findOrdersByStoreId(store_id);
        if (CollectionUtils.isEmpty(ordersByStoreId)){
            return null;
        }
        return ordersByStoreId;
    }

    @RequestMapping("/PurchaseUserToday/{store_id}")
    List<Long> findPurchaseUserToday(@PathVariable(value = "store_id") Long store_id,@RequestParam(value = "today") String today){
        List<Long> purchaseUserToday = orderService.findPurchaseUserToday(store_id, today);
        if (CollectionUtils.isEmpty(purchaseUserToday)){
            return null;
        }
        return purchaseUserToday;
    }

    @RequestMapping("/PurchaseUserTotal/{store_id}")
    List<Long> findPurchaseUserTotal(@PathVariable(value = "store_id") Long store_id){
        List<Long> purchaseUserTotal = orderService.findPurchaseUserTotal(store_id);
        if (CollectionUtils.isEmpty(purchaseUserTotal)){
            return null;
        }
        return purchaseUserTotal;
    }
}
